app.controller('eventscontroller', ['$scope', '$parse', '$http', function($scope, $parse, $http)
{
	$scope.$on('translations', function(event, args) {
		console.info('Event translations received');
		$scope.translations = args.translations.response;
		$scope.getAllStatesEventsCommand();
	});
	
	$scope.$on('eventStatesReceived', function(event, args) {
		console.info('Event states received');
		$scope.getEventsCommand();
	});
	
	$scope.$on('eventsReceived', function(event, args) {
		console.info('Events received');
		$scope.getValidEventSubscriptionsForPlannedEventCommand();
	});
	
	function convertToPascalCase() {
		return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}
	
	function convertToLower() {
		return this.toLowerCase(); 
	}

	String.prototype.toLower = convertToLower;
	String.prototype.toPascalCase = convertToPascalCase;
	
	/**
	* Get all event attachments
	*/
	$scope.getEventAttachmentsCommand = function(eventId)
	{
		console.info("getEventAttachmentsCommand - called"); 
		$scope.loadingEventAttachments = true;	
		$scope.eventAttachments = [];
		
		$http.post($scope.servicebase, { "service" : "getEventAttachments", "eventId" : eventId}).
		success(function(data, status) 
		{
			console.info("getEventAttachmentsCommand - call success"); 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'danger');
			}
			else
			{
				$scope.eventAttachments = data.response;
				$scope.loadingEventAttachments = false;
			}
		})
		.
		error(function(data, status) 
		{
			console.error("getEventAttachmentsCommand - call failed"); 	
			$scope.loadingEventAttachments = false;	
			console.error("getEventAttachmentsCommand - data : " + $scope.data); 				
		});
	}
	
	/**
	* Download an attachment 
	*/
	$scope.downloadAttachmentCommand = function(eventAttachment)
	{
		console.info("downloadAttachmentCommand - called"); 	
		
		console.info("downloadAttachmentCommand - " + eventAttachment.AttachmentName); 
			
		$http.post($scope.servicebase, { "service" : "createTempAttachmentFromBinary", "eventAttachmentId" : eventAttachment.Id, "attachmentName" : eventAttachment.AttachmentName }).
		success(function(data, status) 
		{
			alert(JSON.stringify(data));
			console.info("downloadAttachmentCommand - call sucess");
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			$scope.messageUpdateEventVisible = true;
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger', 'messageUpdateEvent');
			}
			else
			{
				var url = JSON.parse(data);
				$scope.downloadUrl = url;
				$scope.canDownloadAttachment = true;
				$scope.setMessageCommand('Le document est prêt a être téléchargé', 'success', 'messageUpdateEvent');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("downloadAttachmentCommand - call failed"); 
			$scope.canDownloadAttachment = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("downloadAttachmentCommand - data : " + $scope.data); 		
		});
	}
	
	/**
	* Delete an attachment 
	*/
	$scope.deleteAttachmentCommand = function(eventAttachment)
	{
		console.info("deleteAttachmentCommand - called"); 

		$http.post($scope.servicebase, { "service" : "deleteEventAttachment", "id" : eventAttachment.Id}).
		success(function(data, status) 
		{
			console.info("deleteAttachmentCommand - call success"); 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'danger');
			}
			else
			{
				$scope.getEventAttachmentsCommand(eventAttachment.Event.Id);
			}
		})
		.
		error(function(data, status) 
		{
			console.error("deleteAttachmentCommand - call failed"); 	
			$scope.loadingEventAttachments = false;	
			console.error("deleteAttachmentCommand - data : " + $scope.data); 				
		});
	}
	
	/**
	* Attach an event attachment
	*/
	$scope.attachEventAttachmentsCommand = function(eventId)
	{
		try
		{
			console.info("attachEventAttachmentCommand - called with id event : " + eventId + " and " + $scope.attachments.length + " attachments");
			
			$scope.attachments.forEach(function(attachment) 
			{
				var fd = new FormData();
				fd.append("service", "attachEventAttachment");
				fd.append("eventId", eventId);
				fd.append("file", attachment);

				$http.post($scope.servicebase,
					fd,
					{ 
						withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
					}
				).
				success(function(data, status) 
				{
					console.debug("Résultat du service attachEventAttachment " + JSON.stringify(data));
					console.info("attachEventAttachmentCommand - call success"); 
					$scope.messageUpdateEventVisible = true;
					if(data.isFailed == true)
					{
						$scope.setMessageCommand(data.exception, 'warning', 'messageUpdateEvent');
					}
					else
					{
						$scope.attachments = [];
						$scope.setMessageCommand('Pièce jointe attachée.', 'success', 'messageUpdateEvent');
					}
					$scope.poster = undefined;
				})
				.
				error(function(data, status) 
				{
					alert("Erreur dans l'appel du service attachEventAttachment " + JSON.stringify(data));
					console.error("attachEventAttachmentCommand - call failed"); 	
					$scope.setMessageCommand('Ajout d\'une pièce jointe en échec.', 'danger');			
					console.error("attachEventAttachmentCommand - data : " + $scope.data);			
				});
			});
		}
		catch(exception)
		{
			console.error("Erreur dans attachEventAttachmentsCommand : " + exception.message);
		}
	}
	
	/**
	* Set attachments on the event
	*/
	$scope.setAttachmentsCommand = function(files)
	{
		console.info("setAttachmentsCommand called with " + files.length + " files");
		
		$scope.attachments = [];
		
		for (var index = 0; index < files.length; index++) {
			console.debug('iteration on file n° ' + index);
			var file = files[index];
			$scope.attachments.push(file);
		}
		
		console.debug("setAttachmentsCommand set attachments array with " + $scope.attachments.length + " files");
		
		$scope.attachEventAttachmentsCommand($scope.editEvent.Id);
	};
	
	/**
	* Get all event subscriptions validate for planned event
	*/
	$scope.getValidEventSubscriptionsForPlannedEventCommand = function()
	{
		console.info("getValidEventSubscriptionsForPlannedEventCommand - called"); 
		$scope.validEventSubscriptionsForPlannedEvents = [];
		$http.post($scope.servicebase, { "service" : "getValidEventSubscriptionsForPlannedEvent"}).
		success(function(data, status) 
		{
			console.info("getValidEventSubscriptionsForPlannedEventCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			
			$scope.validEventSubscriptionsForPlannedEvents = $scope.data.response;

			$scope.validEventSubscriptionsForPlannedEvents.forEach(function(eventSubscription) {
				$scope.UIEvents.forEach(function(UIEvent) {
					if(eventSubscription.Event.Id == UIEvent.DALObject.Id)
					{
						UIEvent.numberOfSubscriptions++;
					}
				});
			});
		})
		.
		error(function(data, status) 
		{
			console.error("getValidEventSubscriptionsForPlannedEventCommand - call failed"); 	
			$scope.loadingEvents = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("getValidEventSubscriptionsForPlannedEventCommand - data : " + $scope.data); 				
		});
	}
	
	/**
	* Edit participants
	*/
	$scope.editParticipantsCommand = function(event)
	{
		$scope.$broadcast('eventReceived', {
			event: event
		});
	
		$('#participants').modal('show');
	}
	
	/**
	* Add event command 
	*/
	$scope.addEventCommand = function()
	{
		try
		{
			console.info("addEventCommand - called"); 
			$scope.canAddEvent = false;
			$scope.addEvent_StartDate = $('#newEventStartDate').val();
			$scope.addEvent_StartTime = $('#newEventStartTime').val();
			$scope.addEvent_EndDate = $('#newEventEndDate').val();
			$scope.addEvent_EndTime = $('#newEventEndTime').val();
			
			$scope.addEvent_NumberOfPlaces = $scope.addEvent_IsUnlimitedPlaces ? -1 : $('#addEvent_NumberOfPlaces').val();
			
			if($scope.addEvent_Title == "" || $scope.addEvent_Title == undefined)
			{
				throw "Le titre de l'événement est obligatoire.";
			}
			
			if($scope.addEvent_StartDate == "")
			{
				throw "La date de l'événement est obligatoire.";
			}
			
			$scope.addEvent_IsSubscriptionValidationRequired = ($scope.addEvent_IsSubscriptionValidationRequired == true) ? 1 : 0;
			
			$http.post($scope.servicebase, { "service" : "addEvent", "title" : $scope.addEvent_Title.toPascalCase(), "description" : $scope.addEvent_Description, "startDate" : $scope.addEvent_StartDate, "startTime" : $scope.addEvent_StartTime, "endDate" : $scope.addEvent_EndDate, "endTime" : $scope.addEvent_EndTime, "numberOfPlaces" : $scope.addEvent_NumberOfPlaces, "location" : $scope.addEvent_Location, "isSubscriptionValidationRequired" : $scope.addEvent_IsSubscriptionValidationRequired }).
			success(function(data, status) 
			{
				console.info("addEventCommand - call success"); 
				$scope.status = status;
				$scope.data = data;
				$scope.result = data; 
				$scope.loadingArticles = false;
				
				if(data.isFailed == true)
				{
					$scope.setMessageCommand($scope.data.exception, 'danger');
				}
				
				$scope.messageAddEventVisible = true;
				$scope.setMessageCommand('Evénement ajouté en base de données', 'success', 'messageAddEvent');
				
				if($scope.poster != undefined)
				{
					$scope.attachPosterToEventCommand(data.response.Id);
				}
				
				$scope.events.push($scope.data.response);
				
				var presentationEvent = new Event($scope.data.response);
				$scope.UIEvents.push(presentationEvent);
				
				$scope.canAddEvent = true;
				
				$("#addEvent").modal('hide');
				
				$scope.setMessageCommand('L\'événement a bien été ajouté. Il sera en ligne une fois positionné sur l\'état "planifié" .', 'warning');
			})
			.
			error(function(data, status) 
			{
				console.error("addEventCommand - call failed"); 	
				$scope.canAddEvent = true;
				$scope.data = data || "Request failed";
				$scope.status = status;			
				console.error("addEventCommand - data : " + $scope.data); 				
			});
		}
		catch(err) 
		{
			$scope.messageAddEventVisible = true;
			$scope.canAddEvent = true;
			$scope.setMessageCommand(err, 'danger', 'messageAddEvent');
		}
	};
	
	/**
	* Delete the selected event
	*/
	$scope.deleteEventCommand = function(event)
	{
		console.info("deleteEventCommand - called"); 
		$http.post($scope.servicebase, { "service" : "deleteEvent", "id" : event.Id }).
		success(function(data, status) 
		{
			console.info("deleteEventCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			var index = $scope.events.indexOf(event);
			if (index > -1) 
			{
				$scope.events.splice(index, 1);
				$scope.UIEvents.splice(index, 1);
			}
			$("#confirmDeleteEvent").modal('hide');
		})
		.
		error(function(data, status) 
		{
			console.error("deleteEventCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("deleteEventCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Cancel the event deletion
	*/
	$scope.cancelDeleteEventCommand = function()
	{
		$("#confirmDeleteEvent").modal('hide');
	};
	
	/**
	* Prepare to add an event
	*/
	$scope.prepareAddEventCommand = function()
	{
		$("#addEvent").modal('show');
	};
	
	/**
	* Set a poster on the event
	*/
	$scope.setPosterCommand = function(file)
	{
		console.info("setPosterCommand called ");

		var r = new FileReader();

		r.onload = function(e) 
		{ 
			var contents = e.target.result;
			$scope.poster = file;
			$scope.hasPoster = true;
			
			if($scope.editEvent != undefined)
			{
				$scope.attachPosterToEventCommand($scope.editEvent.Id);
			}
		}
		  
		r.readAsText(file);
	};
	
	/**
	* Prepare to edit the user
	*/
	$scope.prepareEditEventCommand = function(event)
	{
		console.info("Set all event informations");
		
		$scope.editEvent = event;
		
		$scope.getEventAttachmentsCommand(event.Id);
		
		if($scope.archives != undefined)
		{
			var index = 0;
			var isfound = false;
			$scope.archives.forEach(function(archive) {
				if(archive.Name == event.ArchiveName && isfound == false)
				{
					isfound = true;
					return;
				}
				if(isfound == false)
				{
					index++;
				}
			});
			
			$scope.editEvent.ArchiveName = $scope.archives[index];
		}
		
		var formattedStartDate = $scope.parseDate(event.StartDate);
		var formattedEndDate = $scope.parseDate(event.EndDate);

		$('#controlEditStartDate').val(formattedStartDate);
		$('#controlEditEndDate').val(formattedEndDate);
		$scope.editEvent.StartDate = $('#controlEditStartDate').val();
		$scope.editEvent.EndDate = $('#controlEditEndDate').val();

		$scope.editEventIsUnlimitedPlaces = (event.NumberOfPlaces == -1) ? true : false;
		$scope.editEventHasPoster = ($scope.editEvent.Picture == undefined || $scope.editEvent.Picture == "") ? false : true; 
		
		$("#editEvent").modal('show');
	};
		
	/**
	* Update the event command
	*/
	$scope.updateEventCommand = function()
	{
		console.info("updateEventCommand - called"); 
		
		$scope.canAddEvent = false;
		
		try
		{
			if($scope.editEventTitle == "")
			{
				throw "Le titre de l'événement est obligatoire.";
			}
			
			$scope.editEventNumberOfPlaces = $scope.editIsUnlimitedPlaces ? -1 : $('#editNumberOfPlaces').val();
			$scope.editEvent.StartDate = $('#controlEditStartDate').val();
			$scope.editEvent.StartTime = $('#controlEditStartTime').val();
			$scope.editEvent.EndDate = $('#controlEditEndDate').val();
			$scope.editEvent.EndTime = $('#controlEditEndTime').val();
			var state = $scope.eventStates.indexOf($scope.editEvent.State);
			$scope.editEvent.ArchiveName = ($scope.editEvent.ArchiveName == undefined) ? '' : $scope.editEvent.ArchiveName.Name;
			
			$http.post($scope.servicebase, { "service" : "updateEvent", "id" : $scope.editEvent.Id, "title" : $scope.editEvent.Title.toPascalCase(), "description" : $scope.editEvent.Description, "startDate" : $scope.editEvent.StartDate, "startTime" : $scope.editEvent.StartTime, "endDate" : $scope.editEvent.EndDate, "endTime" : $scope.editEvent.EndTime, "numberOfPlaces" : $scope.editEvent.NumberOfPlaces, "archiveName" : $scope.editEvent.ArchiveName, "state" : state, "location" : $scope.editEvent.Location }).
			success(function(data, status) 
			{
				console.info("updateEventCommand - call success"); 
				$scope.status = status;
				$scope.data = data;
				$scope.result = data; 
				if(data.isFailed == true)
				{
					$scope.messageUpdateEventVisible = true;
					$scope.setMessageCommand($scope.data.exception, 'danger', 'messageUpdateEvent');
				}
				else
				{
					if($scope.poster != undefined)
					{
						$scope.attachPosterToEventCommand(data.response.Id);
					}

					$("#editEvent").modal('hide');
					$scope.getEventsCommand();
					$scope.setMessageCommand("L'événement #" + $scope.editEvent.Id + " a été mis à jour." , 'success');
				}
				
				$scope.canAddEvent = true;
			})
			.
			error(function(data, status) 
			{
				console.error("updateEventCommand - call failed"); 	
				$scope.data = data || "Request failed";
				$scope.status = status;			
				console.error("updateEventCommand - data : " + $scope.data); 	
				$scope.canAddEvent = true;				
			});
		}
		catch(err) 
		{
			$scope.messageUpdateEventVisible = true;
			$scope.setMessageCommand(err, 'danger', 'messageUpdateEvent');
		}
	};
	
	/**
	* Attach a poster on an event
	*/
	$scope.attachPosterToEventCommand = function(idEvent)
	{
		console.info("attachPosterToEventCommand - called with id event : " + idEvent);
		
		var fd = new FormData();
		fd.append("service", "attachPosterOnAnEvent");
		fd.append("idEvent", idEvent);
		fd.append("file", $scope.poster);
		
		$http.post($scope.servicebase,
			fd,
			{ 
				withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
			}
		).
		success(function(data, status) 
		{
			console.info("attachPosterToEventCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			$scope.messageUpdateEventVisible = true;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'warning', 'messageUpdateEvent');
			}
			else
			{
				$scope.getEventsCommand();
				$scope.setMessageCommand('Affiche jointe.', 'success', 'messageUpdateEvent');
			}
			$scope.poster = undefined;
		})
		.
		error(function(data, status) 
		{
			console.error("attachPosterToEventCommand - call failed"); 	
			$scope.setMessageCommand('Ajout d\'une affiche en échec.', 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;				
			console.error("attachPosterToEventCommand - data : " + $scope.data);			
		});
	};
	
	/**
	* Get all states event
	*/
	$scope.getAllStatesEventsCommand = function()
	{
		console.info("getAllStatesEventsCommand - called");
		$http.post($scope.servicebase, { "service" : "getEventStates"}).
		success(function(data, status) 
		{
			console.info("getEventStates - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				
				for(var state in $scope.data.response) {
				   $scope.eventStates.push($scope.translations["Events_State_" + state]);
				}
				
				$scope.$broadcast('eventStatesReceived', {
					states: $scope.eventStates 
				});
			}
		})
		.
		error(function(data, status) 
		{
			console.error("getEventStates - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;
			console.error("getEventStates - data : " + $scope.data);		
		});
	};
	
	/**
	* Confirm to delete the event
	*/
	$scope.confirmDeleteEventCommand = function(event)
	{
		$scope.currentEvent = event;
		$("#confirmDeleteEvent").modal('show');
	};
		
	/**
	* Get all events
	*/
	$scope.getEventsCommand = function()
	{
		console.info("getEventsCommand - called"); 
		$scope.loadingEvents = true;
		$scope.canAddEvent = false;
		$scope.UIEvents = [];
		$http.post($scope.servicebase, { "service" : "getEvents"}).
		success(function(data, status) 
		{
			console.info("getEventsCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			$scope.loadingEvents = false;
			$scope.canAddEvent = true;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			
			$scope.events = $scope.data.response;
			
			$scope.events.forEach(function(event) {
				event.State = $scope.eventStates[event.State];
			});
			
			//Set UI property
			$scope.events.forEach(function(event) 
			{
				var presentationEvent = new Event(event);
				$scope.UIEvents.push(presentationEvent);
			});
			
			$scope.canAddEvent = true;
			
			$scope.$broadcast('eventsReceived', {
				events: $scope.events
			});
		})
		.
		error(function(data, status) 
		{
			console.error("getEventsCommand - call failed"); 	
			$scope.loadingEvents = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("getEventsCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Get all archives
	*/
	$scope.getArchivesCommand = function()
	{
		console.info("getArchivesCommand - called"); 
		$scope.archives = [];
		$http.post($scope.servicebase, { "service" : "getArchives", "path" : "", "forceToRefresh" : true, "filter" : "" }).
		success(function(data, status) 
		{
			console.info("getArchivesCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			
			$scope.archives = $scope.data.response;
		})
		.
		error(function(data, status) 
		{
			console.error("getArchivesCommand - call failed"); 	
			$scope.loadingEvents = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("getArchivesCommand - data : " + $scope.data); 				
		});
	}
	
	/**
	*	Load the events component
	*/
	$scope.loadEventsComponentCommand = function() 
	{
		console.info("loadEventsComponentCommand - called");
		$scope.addEventHasPoster = false;
		$scope.eventId = undefined;
		$scope.archives = [];
		$scope.events = [];
		$scope.eventAttachments = [];
		$scope.UIEvents = [];
		$scope.poster = undefined;
		$scope.attachments = [];
		$scope.getArchivesCommand();
	};
	
	$scope.loadEventsComponentCommand();
}]);